package cn.lcl.web.servlet;

import cn.lcl.bean.JsonMsg;
import cn.lcl.bean.PageBean;
import cn.lcl.bean.po.Student;
import cn.lcl.factory.ServiceFactory;
import cn.lcl.service.IAdminService;
import cn.lcl.util.JacksonUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;


/**
 * Created by licho on 2017/8/19 0019.
 */
@WebServlet("/ajax/*")
public class AjaxServlet extends BaseServlet {
    private static  final Logger log= Logger.getLogger(AjaxServlet.class);
    private IAdminService service= ServiceFactory.getService(IAdminService.class);
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-type","application/json;charset=UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", "*");//可以用作跨域json
        PageBean<Student> data=service.showStuLists();
        String json= JacksonUtils.converToJson(data);
        log.info(json.trim());
        resp.getWriter().print(json);
    }
    public String delete(HttpServletRequest req, HttpServletResponse resp){
        resp.setHeader("Content-type","application/json;charset=UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", "*");//可以用作跨域jso
        boolean flag=false;
        try {
            Writer w=resp.getWriter();
            String psid=req.getParameter("sid");//获取学号
            Long sid=(Long) ConvertUtils.convert(psid,Long.class);
            flag=service.deleteStu(sid);
           if(!flag){
               w.write(JacksonUtils.converToJson(new JsonMsg(500,"未知错误，删除失败")));
           } else{
               w.write(JacksonUtils.converToJson(new JsonMsg(200,"删除成功")));
           }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
